import { useRef, useEffect, useState } from 'react';

//props哪些值发生变化导致组件更新
export default function usePropsCheck(props: any) {
  const previousProps = useRef<any>();
  const [changesObj, setChangesObj] = useState({});
  useEffect(() => {
    if (previousProps.current) {
      setChangesObj({});
      const allKeys = Object.keys({ ...previousProps.current, ...props });
      allKeys.forEach(key => {
        if (props && previousProps.current[key] !== props[key]) {
          setChangesObj(
            Object.assign(changesObj, {
              [key]: { from: previousProps.current[key], to: props[key] },
            }),
          );
        }
      });
      if (Object.keys(changesObj).length) {
        console.log('[why-did-you-update]', changesObj);
      }
    }
    previousProps.current = props;
  }, [changesObj, props]);
  return changesObj;
}
